package com.ujs.edu.medicine.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.ujs.edu.medicine.dao.*;
import com.ujs.edu.medicine.dataobject.*;
import com.ujs.edu.medicine.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author:
 * @Date: Created in 9:45 2020/8/25
 * Description: 订单控制类
 * Modified By:
 */
@RestController
public class OrderController {

    @Autowired
    YunjiayiOrderMapper yunjiayiOrderMapper;
    @Autowired
    YunjiayiShopMapper yunjiayiShopMapper;
    @Autowired
    YunjiayiAddressMapper yunjiayiAddressMapper;
    @Autowired
    YunjiayiMedicineMapper yunjiayiMedicineMapper;
    @Autowired
    PictureMSMapper pictureMSMapper;
    @Autowired
    YunjiayiUserMapper yunjiayiUserMapper;
    @Autowired
    private HttpServletRequest request;

    private String gettoken() {
        return request.getHeader("Authorization");
    }

    /*获取订单列表*/
    @RequestMapping("/api/shop/orderList")
    public Result orderList(@RequestBody JSONObject obj) {
        Result result = new Result();

        String token = gettoken();
        int myuserid = 0;
        try {
            myuserid = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }

        YunjiayiUser user = yunjiayiUserMapper.selectByPrimaryKey(myuserid);


        List<YunjiayiOrder> orders=null;
        try {

            if (user.getIdentityId().equals(5)) {
                orders=yunjiayiOrderMapper.selectByShopId(myuserid);
            }else {
                orders = yunjiayiOrderMapper.selectByUserId(myuserid);
            }

            YunjiayiShop shop = new YunjiayiShop();
            List<Object> list = new ArrayList<>();
            JSONObject object = null;
            JSONObject shop1 = null;


            for (YunjiayiOrder order : orders) {
                object = new JSONObject();


                if ((obj.getInteger("status").toString()).equals(order.getOrderstatus())) {
                    object.put("allPrice", order.getAllprice());
                    object.put("ID", Integer.parseInt(order.getOrderstatus()));
                    object.put("time", order.getCreatetime());
                    object.put("orderID", order.getOrderid());

                    shop = yunjiayiShopMapper.selectByPrimaryKey(order.getShopid());
                    shop1 = new JSONObject();
                    shop1.put("shopname", shop.getShopname());
                    shop1.put("shopimage", shop.getShopimage());
                    shop1.put("shopid", shop.getShopid());

                    object.put("shop", shop1);
                    list.add(object);
                }

                if (obj.getInteger("status") == 0) {
                    object.put("allPrice", order.getAllprice());
                    object.put("ID", Integer.parseInt(order.getOrderstatus()));
                    object.put("time", order.getCreatetime());
                    object.put("orderID", order.getOrderid());

                    shop = yunjiayiShopMapper.selectByPrimaryKey(order.getShopid());
                    shop1 = new JSONObject();
                    shop1.put("shopname", shop.getShopname());
                    shop1.put("shopimage", shop.getShopimage());
                    shop1.put("shopid", shop.getShopid());

                    object.put("shop", shop1);
                    list.add(object);
                }
            }

            result.setCode(0);
            result.setMessage("查询成功");
            result.setData(list);
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("查询失败");
        }

        return result;
    }


    /*获取订单状态*/
    @RequestMapping("/api/order/orderStatus")
    public Result orderStatus(@RequestParam("orderId") Integer orderId) {
        Result result = new Result();

        String token = gettoken();
        int myuserid = 0;
        try {
            myuserid = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
        }

        YunjiayiOrder order = yunjiayiOrderMapper.selectByPrimaryKey(orderId);

        if (order != null) {
            result.setCode(0);
            result.setMessage("查询成功");
            result.setData(order.getOrderstatus());
        } else {
            result.setCode(1);
            result.setMessage("没有这个订单");
        }

        return result;
    }

    /*修改订单状态*/
    @RequestMapping("/api/shop/orderstatus")
    public Result uporderStatus(@RequestBody Map<String, String> map) {
        Result result = new Result();

        String token = gettoken();
        int myuserid = 0;
        try {
            myuserid = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }

        YunjiayiOrder order = yunjiayiOrderMapper.selectByPrimaryKey(Integer.parseInt(map.get("ID")));
        if (order == null) {
            result.setCode(1);
            result.setMessage("没有这个订单");
            return result;
        }

        Integer status = Integer.parseInt(map.get("current_status"));
        status = status + 1;
        order.setOrderstatus(status.toString());
        int ordst = yunjiayiOrderMapper.updateByPrimaryKey(order);
        if (ordst == 1) {
            JSONObject object = new JSONObject();

            object.put("next_status", Integer.parseInt(order.getOrderstatus()));

            result.setCode(0);
            result.setMessage("修改成功");
            result.setData(object);
        } else {
            result.setCode(1);
            result.setMessage("修改失败");
        }
        return result;
    }


    /*创建订单*/
    @RequestMapping("/api/shop/createOrder")
    public Result createOrder(@RequestBody JSONObject object) {
        Result result = new Result();

        String token = gettoken();
        int myuserid = 0;
        try {
            myuserid = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }

        YunjiayiOrder order = new YunjiayiOrder();
        YunjiayiAddress address = new YunjiayiAddress();

        try {


            order.setMedicineid(object.getJSONArray("medicineID").toString());
            order.setUserid(myuserid);
            order.setAllprice(new BigDecimal(object.getString("allprice")));
            order.setOrderstatus("1");
            order.setShopid(object.getInteger("shopID"));

            address.setAddress(object.getString("address"));
            address.setAduserid(myuserid);
            address.setDefaultaddress(false);
            address.setTelephone(object.getString("phonenumber"));
            address.setNote("无");

            int ord = yunjiayiOrderMapper.insert(order);
            int addr = yunjiayiAddressMapper.insert(address);
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("传入信息有错误");
            return result;
        }

        JSONObject object1 = new JSONObject();
        YunjiayiOrder order1 = yunjiayiOrderMapper.selectByPrimaryKey(order.getOrderid());

        if (order1 != null) {
            object1.put("orderID", order1.getOrderid());
            System.out.println(order1.getOrderstatus());
            object1.put("ID", Integer.parseInt(order1.getOrderstatus()));
            object1.put("time", order1.getCreatetime());

            result.setCode(0);
            result.setMessage("创建成功");
            result.setData(object1);
        } else {
            result.setCode(1);
            result.setMessage("创建失败");
        }

        return result;
    }


    /*订单详细信息*/
    @RequestMapping("/api/shop/orderInfo")
    public Result orderInfo(@RequestParam("orderId") Integer orderId) {
        Result result = new Result();
        JSONObject object = new JSONObject();
        JSONObject shopObj = new JSONObject();
        JSONObject medicineObj = new JSONObject();
        JSONObject userInfo = new JSONObject();
        List<JSONObject> medicineList = new ArrayList<>();

        String token = gettoken();
        int myuserid = 0;
        try {
            myuserid = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }


        try {
            YunjiayiOrder order = yunjiayiOrderMapper.selectByPrimaryKey(orderId);
            YunjiayiShop shop = yunjiayiShopMapper.selectByPrimaryKey(order.getShopid());
            order.setMedicineList(JSONObject.parseArray(order.getMedicineid()));


            object.put("deliverFee", shop.getDeliveryfee());
            object.put("allPrice", order.getAllprice());
            object.put("id", Integer.parseInt(order.getOrderstatus()));

            shopObj.put("name", shop.getShopname());
            shopObj.put("shopID", shop.getShopid());
            shopObj.put("phone_number", shop.getTelephone());

            object.put("shop", shopObj);

            for (MedicineNumber medicineNumber : JSONObject.parseArray(order.getMedicineid()).toJavaList(MedicineNumber.class)) {
                YunjiayiMedicine medicine = yunjiayiMedicineMapper.selectByPrimaryKey(medicineNumber.getMedicineid());
                medicine.setPicture(pictureMSMapper.selectByMedicineId(medicineNumber.getMedicineid()));

                medicineObj.put("mainpicture", medicine.getPicture().get(0));
                medicineObj.put("medicine_name", medicine.getMename());
                medicineObj.put("number", medicineNumber.getNumber());
                medicineObj.put("price", medicine.getPrice());

                medicineList.add(medicineObj);
            }

            object.put("medicine_list", medicineList);
            object.put("time", order.getCreatetime());

            YunjiayiUser user = yunjiayiUserMapper.selectByPrimaryKey(myuserid);
            List<YunjiayiAddress> address = yunjiayiAddressMapper.selectAddressByuId(myuserid);
            userInfo.put("name", user.getUsername());
            userInfo.put("address", address.get(0).getAddress());
            userInfo.put("phone", address.get(0).getTelephone());

            object.put("user_info", userInfo);

            result.setCode(0);
            result.setMessage("查询成功");
            result.setData(object);
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("查询失败");
        }

        return result;
    }

}
